import React, { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
// import { LeftOutline, ExclamationCircleOutlined } from 'antd-mobile-icons'
import styles from './Deposit.module.css'
import axios from '../../axios'

export default function Deposit() {
  const navigate = useNavigate()
  const location = useLocation()
  const [amount, setAmount] = useState('')
  const [customAmount, setCustomAmount] = useState(false)
  const [loading, setLoading] = useState(false)
  const [selectedPayment, setSelectedPayment] = useState('alipay') // 默认选择支付宝
  const [orderId, setOrderId] = useState(null)
  const [paypalOrderId, setPaypalOrderId] = useState(null)
  const [userInfo, setUserInfo] = useState({})
  const [loadingUserInfo, setLoadingUserInfo] = useState(true)

  // 从本地存储获取用户ID
  const userId = localStorage.getItem('userId') || localStorage.getItem('user') || ''

  // 获取用户信息和洋币余额
  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        setLoadingUserInfo(true)
        const response = await axios.get('/index', { params: { id: userId } })
        if (response.data && response.data.data) {
          setUserInfo(response.data.data)
        }
      } catch (error) {
        console.error('获取用户信息失败', error)
      } finally {
        setLoadingUserInfo(false)
      }
    }

    if (userId) {
      fetchUserInfo()
    }
  }, [userId])

  // 检查是否是支付完成后的返回
  useEffect(() => {
    const query = new URLSearchParams(location.search)
    const orderNo = query.get('out_trade_no')
    const paymentType = query.get('payment_type') // 获取支付类型参数
    const token = query.get('token') // PayPal返回的token
    const payerId = query.get('PayerID') // PayPal返回的付款人ID
    
    // 如果有订单号参数，说明是从支付页面跳转回来的
    if (orderNo) {
      // 查询支付宝支付结果
      queryPaymentResult(orderNo)
    } else if (token && payerId) {
      // 处理PayPal支付回调 - PayPal返回token和PayerID表示支付授权成功
      handlePayPalReturn(token, payerId)
    }
  }, [location])

  // 查询支付结果
  const queryPaymentResult = async (orderNo) => {
    try {
      const response = await axios.get(`/api/alipay/query?orderId=${orderNo}`)
      if (response.data.code === 200) {
        const result = response.data.data
        // 检查支付状态
        if (result && result.alipay_trade_query_response) {
          const tradeStatus = result.alipay_trade_query_response.trade_status
          if (tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED') {
            alert('支付成功！')
            // 跳转到个人中心
            navigate('/my')
          } else {
            alert('支付未完成，请重新支付')
          }
        }
      }
    } catch (error) {
      console.error('查询支付结果失败', error)
      alert('查询支付结果失败，请联系客服')
    }
  }

  // 处理PayPal支付回调
  const handlePayPalReturn = async (token, payerId) => {
    try {
      if (paypalOrderId) {
        // 验证PayPal支付结果
        const response = await axios.post('/api/paypal/capture', {
          paypalOrderId: paypalOrderId,
          userId
        })
        
        if (response.data.code === 200) {
          alert('PayPal支付成功！')
          // 跳转到个人中心
          navigate('/my')
        } else {
          console.error('PayPal支付未完成', response.data)
          alert('支付未完成，请重新支付')
        }
      } else {
        // 查询PayPal支付结果
        queryPayPalResult(token)
      }
    } catch (error) {
      console.error('处理PayPal支付结果失败', error)
      alert('处理支付结果失败，请联系客服')
    }
  }

  // 查询PayPal支付结果
  const queryPayPalResult = async (token) => {
    try {
      if (!paypalOrderId) {
        console.error('无PayPal订单ID，无法查询')
        return
      }
      
      // 调用PayPal支付查询接口
      const response = await axios.get(`/api/paypal/query?paypalOrderId=${paypalOrderId}`)
      if (response.data.code === 200) {
        const result = response.data.data
        // 检查支付状态
        if (result && result.orderStatus) {
          const status = result.orderStatus
          if (status === 'COMPLETED') {
            alert('PayPal支付成功！')
            // 跳转到个人中心
            navigate('/my')
          } else {
            alert('支付未完成，请重新支付')
          }
        }
      }
    } catch (error) {
      console.error('查询PayPal支付结果失败', error)
      alert('查询支付结果失败，请联系客服')
    }
  }

  // 预设充值选项（人民币金额）
  const depositOptions = [10, 20, 50, 100]

  // 只保留洋币
  const yangCoin = {
    id: 'YANG', 
    name: '洋币', 
    icon: '¥', 
    address: 'YC98t1WpEZ73CNmQviecrnyiWrnqRhWNLy'
  }

  const handleAmountChange = (e) => {
    const value = e.target.value
    if (/^\d*\.?\d*$/.test(value) || value === '') {
      // 限制最大充值金额为99999
      if (value === '' || parseFloat(value) <= 99999) {
        setAmount(value)
      }
    }
  }

  const selectPresetAmount = (value) => {
    setAmount(value.toString())
    setCustomAmount(false)
  }

  const enableCustomAmount = () => {
    setCustomAmount(true)
    setAmount('')
  }

  // 创建支付宝订单
  const createAlipayOrder = async () => {
    try {
      setLoading(true)
      const jia = await axios.post('/jia',{id:localStorage.getItem('user'),amount:parseFloat(amount)})
      const response = await axios.post('/api/alipay/create', {
        amount: parseFloat(amount),
        userId
      })
      
      if (response.data.code === 200) {
        
        const { orderId, payUrl } = response.data.data
        setOrderId(orderId)
        
        // 跳转到支付宝支付页面
        window.location.href = payUrl
      } else {
        alert('创建订单失败：' + response.data.message)
      }
    } catch (error) {
      console.error('创建订单失败', error)
      alert('创建订单失败，请稍后再试')
    } finally {
      setLoading(false)
    }
  }

  // 创建PayPal支付订单
  const createPayPalOrder = async () => {
    try {
      setLoading(true)
      // 先记录充值（实际项目中应该在支付成功后再记录）
      const jia = await axios.post('/jia',{id:localStorage.getItem('user'),amount:parseFloat(amount)})
      
      // 调用后端创建PayPal支付订单接口
      const response = await axios.post('/api/paypal/create', {
        amount: parseFloat(amount),
        userId
      })
      
      if (response.data.code === 200) {
        const { orderId, paypalOrderId, approveLink, originalAmount, usdAmount, isSandbox } = response.data.data
        setOrderId(orderId)
        setPaypalOrderId(paypalOrderId) // 保存PayPal订单ID用于后续查询
        
        // 提示用户PayPal支付信息
        alert(`PayPal支付\n\n您的${originalAmount}元人民币将按汇率转换为约${usdAmount}美元`);
        
        // 跳转到PayPal支付页面
        window.location.href = approveLink
      } else {
        alert('创建PayPal支付订单失败：' + response.data.message)
      }
    } catch (error) {
      console.error('创建PayPal支付订单失败', error)
      alert('创建PayPal支付订单失败，请稍后再试')
    } finally {
      setLoading(false)
    }
  }

  const handleDeposit = () => {
    if (!amount || parseFloat(amount) <= 0) {
      alert('请输入有效金额')
      return
    }

    if (selectedPayment === 'alipay') {
      createAlipayOrder()
    } else if (selectedPayment === 'paypal') {
      // 调用PayPal支付
      createPayPalOrder()
    } else {
      alert(`已选择${selectedPayment}支付方式，将获得${parseFloat(amount) * 10}洋币!`)
    }
  }

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.backButton} onClick={() => navigate(-1)}>
          
        </div>
        <h1 className={styles.title}>洋币充值</h1>
        <div className={styles.spacer}></div>
      </div>
      
      {/* 洋币余额显示 */}
      <div className={styles.balanceCard}>
        <div className={styles.balanceHeader}>当前洋币余额</div>
        <div className={styles.balanceAmount}>
          {loadingUserInfo ? (
            <span className={styles.loading}>加载中...</span>
          ) : (
            <span className={styles.amountValue}>
              {userInfo.yangcoin || userInfo.money || 0} <span className={styles.amountUnit}>洋币</span>
            </span>
          )}
        </div>
      </div>

      <div className={styles.card}>
        <div className={styles.exchangeRate}>
          <p className={styles.exchangeRateText}>兑换比例：1元人民币 = 10洋币</p>
        </div>

        <div className={styles.presetAmounts}>
          <label className={styles.label}>选择充值金额（人民币）</label>
          <div className={styles.amountOptions}>
            {depositOptions.map(option => (
              <div 
                key={option}
                onClick={() => selectPresetAmount(option)}
                className={`${styles.amountOption} ${!customAmount && amount === option.toString() ? styles.selectedAmount : ''}`}
              >
                {option}元
              </div>
            ))}
            <div 
              onClick={enableCustomAmount}
              className={`${styles.amountOption} ${customAmount ? styles.selectedAmount : ''}`}
            >
              自定义
            </div>
          </div>
        </div>

        {customAmount && (
          <div className={styles.amountSection}>
            <label className={styles.label}>自定义金额（最多99999元）</label>
            <div className={styles.amountInput}>
              <input 
                type="text" 
                value={amount} 
                onChange={handleAmountChange}
                placeholder="0.00"
                className={styles.input}
                autoFocus
              />
              <div className={styles.currencySymbol}>元</div>
            </div>
          </div>
        )}

        <div className={styles.yangcoinAmount}>
          <p className={styles.yangcoinText}>
            将获得 <span className={styles.yangcoinValue}>{amount ? parseFloat(amount) * 10 : 0}</span> 洋币
          </p>
        </div>

        <div className={styles.addressSection}>
          <div className={styles.addressHeader}>
            <label className={styles.label}>充值方式</label>
            <div className={styles.warningIcon}>
              {/* <ExclamationCircleOutlined fontSize={16} /> */}
              <span className={styles.warningText}>请选择支付方式完成充值</span>
            </div>
          </div>
          
          <div className={styles.paymentOptions}>
            <div 
              className={`${styles.paymentOption} ${selectedPayment === 'alipay' ? styles.selectedPayment : ''}`}
              onClick={() => setSelectedPayment('alipay')}
            >
              <div className={styles.paymentName}>支付宝</div>
            </div>
            <div 
              className={`${styles.paymentOption} ${selectedPayment === 'paypal' ? styles.selectedPayment : ''}`}
              onClick={() => setSelectedPayment('paypal')}
            >
              <div className={styles.paymentName}>PayPal</div>
            </div>
          </div>
        </div>

        <div className={styles.infoBox}>
          <p className={styles.infoText}>
            {' '}
            充值完成后洋币将自动添加到您的账户中，如有问题请联系客服。
          </p>
        </div>

        <button 
          className={styles.depositButton} 
          onClick={handleDeposit}
          disabled={loading}
        >
          {loading ? '处理中...' : '确认充值'}
        </button>
      </div>
    </div>
  )
}
